﻿using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TemplateEmailSender
{
    static class MailsList
    {
        public static List<string> mailsList = new List<string>();
        private static System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
        private static System.Net.Mail.SmtpClient smtp;
        public static void SendMessage()
        {
                smtp.Send(message);
        }
        public static void ConstructMessage(string senderMail, string subject, string fileName, int i)
        {
            Template.output = Template.file;
            for (int x = 0; x < Template.menu.Count; x++)
            {
                Template.output = Template.output.Replace('[' + Template.menu[x] + ']', Entry.items[x][i]);
            }
            message.To.Add(mailsList[i]);
            message.Subject = subject;
            message.From = new System.Net.Mail.MailAddress(senderMail);
            message.Body = Template.output;
            message.IsBodyHtml = true;
            message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
            if (fileName != "someAttachment")
            {
                message.Attachments.Add(new Attachment(fileName));
            }
        }

        public static void ConstructSMTP(string SMTP, string senderMail, string password)
        {
            smtp = new System.Net.Mail.SmtpClient(SMTP, 25);
            smtp.Credentials = new NetworkCredential(senderMail, password);
            smtp.EnableSsl = true;
        }
        public static bool GetMails(string fileName)
        {
            string conStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +
                ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
            OleDbConnection entryFile = new OleDbConnection(conStr);
            using (entryFile)
            {
                try
                {
                    entryFile.Open();
                    OleDbCommand getEntries = new OleDbCommand("SELECT * FROM [mails$]", entryFile);
                    OleDbDataReader result;
                    result = getEntries.ExecuteReader();
                    while (result.Read())
                    {
                        mailsList.Add(result.GetString(0));
                    }
                    return true;
                }
                catch (Exception)
                {

                    MessageBox.Show("The excel sheet in the file must be named: mails !!!");
                    return false;
                }




            }
        }
    }
}
